package com.su.sweet.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.su.sweet.model.SMenu;
import com.su.sweet.mapper.SMenuMapper;
import com.su.sweet.service.ISMenuService;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.solon.annotation.Db;
import org.noear.solon.annotation.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author su
 * @since 2025-01-02
 */
@Component
public class SMenuServiceImpl implements ISMenuService {

    @Db
    private SMenuMapper sMenuMapper;

    @Override
    public List<Map<String, Object>> findMenus(Integer userId) {
        return List.of();
    }

    @Override
    public boolean saveMenu(SMenu menu) {
        return sMenuMapper.insert(menu) > 0;
    }

    @Override
    public boolean deleteMenu(Long id) {
        return sMenuMapper.deleteById(id) > 0;
    }

    @Override
    public boolean updateMenu(SMenu menu) {
        return sMenuMapper.updateById(menu) > 0;
    }

    @Override
    public SMenu getMenuById(Long id) {
        return sMenuMapper.selectById(id);
    }

    @Override
    public List<SMenu> getMenuTree(String menuName, String menuCode) {
        // 构建查询条件
        QueryWrapper<SMenu> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(menuName)) {
            queryWrapper.like("menu_name", menuName);
        }
        if (StringUtils.isNotBlank(menuCode)) {
            queryWrapper.like("menu_code", menuCode);
        }
        // 查询符合条件的菜单
        List<SMenu> allMenus = sMenuMapper.selectList(queryWrapper);
        // 构建树形结构
        return buildMenuTree(allMenus, 0L);
    }

    /**
     * 递归构建菜单树
     * @param allMenus 所有菜单列表
     * @param parentId 父菜单ID
     * @return 树形菜单列表
     */
    private List<SMenu> buildMenuTree(List<SMenu> allMenus, Long parentId) {
        List<SMenu> tree = new ArrayList<>();
        for (SMenu menu : allMenus) {
            if (menu.getMenuParentId().equals(parentId)) {
                List<SMenu> children = buildMenuTree(allMenus, menu.getMenuId());
                if (!children.isEmpty()) {
                    menu.setChildren(children);
                }
                tree.add(menu);
            }
        }
        return tree;
    }
}
